//http://localhost/bmw/service.php?site=null&overdue=null&aftertime=null&counter=0
var delay = 60000;
var timer;
var counter;
var scrollerInterval;

$(document).ready(function(){
	getData(2);
	counter = 0;
	//autoResize();
	
	$(window).resize(function() {
		//autoResize();
	});
	
	function autoResize() {
		$("#datatable").css('max-height',$(window).height()-10);
		$("#ad").css('max-height',$(window).height()-7);
		$("#datatable").css('width',$(window).width());
		$("#ad").css('width',$(window).width());
	}
	
	timer = setInterval( function() { getData(2); }, delay );
});

function getData(site_id) {
	var p="site="+($(document).getUrlParam('site')||'')+"&overdue="+($(document).getUrlParam('overdue')||'')+"&aftertime="+($(document).getUrlParam('aftertime')||'')+"&sessionID="+($(document).getUrlParam('sessionID')||'')+"&counter="+(counter||0);
	// test
	// p = "counter=2&overdue=123456&aftertime=123456";
	$.ajax({
		type: "POST",
		url: "Services.aspx?" + p,
		data: { siteid: site_id }
	}).done(function( retdata ) {
	    // json: Needed ListObject: [{Service Advisor Image, SA Name, [list of check-in time, Customer Name, license number, status(waiting,ongoing,ready)]}]
		// console.log(retdata);
	    clearInterval(timer); // clear interval
		if (counter<1000000) counter ++;
		else counter=0;
		
		$("#ad").hide(0);
		
		$("#ad").html("");
		$("#datatablebody").html("");
	    $("#check-in-time .table").html("");
		var delay = retdata.delay || 30000;
		var dispStatusColor = retdata.dispStatusColor && ' Color';
		var colFullscreen = retdata.colFullscreen || 1;
	
		$("#dt span").html(retdata.dt);
	    Cufon.replace('#dt');
	    retdata.tbldata = retdata.tbldata || [];
		if (retdata.tbldata.length > 0) {
			$("#pagetable").show(0);
			$("#dt").show();
			//http://placehold.it/123/123
			$.each(retdata.tbldata, function(i, item) {
			    var workOrders = item.WorkOrders;
			    var d = "<article><div>"
			    + "<div><img src='" + (item.PictureRef) + "' /></div>"
			    + "<h3>" + item.Name + "</h3>"
			    + "<div class='check-in-time'><table cellpadding='2px' cellspacing='0'>"
			    $.each(workOrders, function(i, item) {
			    var wo = "<tr><td>" + item.Time + "</td><td class='Status " + item.Status + dispStatusColor + "'>" + "<span class='lic'><i class='before'></i><span >" + item.LicenseNo + "</span><i class='after'></i></span></td></tr>"
			            + "<tr><td colspan='2'> <div class = 'cusName'>" + item.CustomerName + "</div></td></tr>";
			            d += wo;
			    });
			    d += "</table></div>" 
			    + "</div></article>";
			    $("#check-in-time .table").append(d);
			    
			});
			//Cufon.replace('#check-in-time .table');
			// Column division
			resizeFullscreen(colFullscreen);
			$(window).unbind('resize').resize(function() {
                resizeFullscreen(colFullscreen);
            });
			
			// Scroll ...
			if (retdata.tbldata.length > colFullscreen) {
		        var scrollerDelay = retdata.scrollerDelay || 0;
		        var scrollerDuration = retdata.scrollerDuration || 1000;
                scroller(scrollerDuration, scrollerDelay);
			} else {
			    // fullscreen;
			}
			
		} else if (retdata['image']) {
		    $("#pagetable").hide(0);// hide at this time
			$("#ad").show(0);
			$("#dt").hide(0);
			$("#ad").html("<img src='" +  retdata['image'] + "' alt='' style='width:100%;' />");
		}
		
		// set interval
		timer = setInterval(function() { getData(2); },delay );	 
		
		$("#debug").html(delay + "ms" + ", " + $(window).width() + " x " + $(window).height());
		
	}).fail(function (jqXHR, textStatus) {
        console.log(jqXHR);
        console.log(textStatus);
  });
}

function resizeFullscreen(cols) {
    var el = $('#check-in-time');
    var elwidth = el.width();
    $('div.horizontal .table article').css("width", elwidth / cols);
}

function scroller(duration, delay) {
    var el = $('#check-in-time div.table');
    var lastEl = $('#check-in-time div.table article:last');
    var firstEl = $('#check-in-time div.table article:first');
    $(el).animate(
        {
            left: '-=' + $(lastEl).width()
        },
        (duration || 1000),
        'linear',
        function() {
            $(el).css("left", 0);
            $(lastEl).after($(firstEl).detach());
            //var text = firstEl.find("h3").text();
            //console.log(text);
            setTimeout(function(){
                scroller(duration, delay)
            }, delay);
        }
    );
}